// pages/course/index.js

import{ getCourseListRequest } from '../../api/main' ;
const courseCacheKey = "courses";
Page({

  data: {
  courseList: [],//虚拟数据
  weekIndexText:['一','二','三','四','五','六','日'],//数字中文化
  startDate:'2025/09/01', //开学日期
  nowWeek:1,
  weekDayCount:7,
  nowMonth:1, //当前月份
  color:['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','0'],
  bgColorList: [
    '#D4E6B5', '#A7C4C2', '#E2CFC4', '#B5D8D4', '#D9C7B8',
    '#C4D7E2', '#B8C9D9', '#E2D4C4', '#C4E2D7', '#D9B8C7',
    '#B5E6D4', '#C7D9B8', '#D4C4E2', '#B8D9C7', '#E2B5D4',
    '#C4B5E6', '#D9E2C4', '#B5C4E2', '#E6D4B5', '#C7B8D9',
    '#D4E2C7', '#B8B5E6', '#E6C4D4', '#C4D9E2', '#D9B5C4',
    '#E2E6B5', '#B5D9E2', '#D4B8E6', '#C7E2D4', '#E6B8D4'
  ]
  },
  onLoad(options) {
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          win: res.windowWidth
        })
        this.getWeekDates();  
        this.getNowWeek()  
        this.getData()
        this.bgColor()
      }
  })},
  getWeekDates(){
    const startDate = new Date(this.data.startDate)//开学日期
    const addTime = (this.data.nowWeek - 1) * 7 *  24 * 60 * 60 * 1000 //当前周
    const firstTime = startDate.getTime() + addTime  //第一天 （时间戳）
    const{ month:nowMonth } = this.getDateObject(new Date(firstTime))
    const weekCalender = []
    for(let i = 0;i < this.data.weekDayCount ; i++ ){
      const date = new Date(firstTime + i * 24 * 60 * 60 *1000)
      const { day }  = this.getDateObject(date)
      weekCalender.push(day)
    }
    this.setData({
      weekCalender,
      nowMonth
    })
  },

  getDateObject(date = new Date()){
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return {
      year,
      month,
      day
    }
  },

  handleNowWeekChange(e) {
    const week1 = e.detail.nowWeek
    this.setData({
      nowWeek:week1// 直接获取 nowWeek 的值
    });
    console.log(week1);
    this.getWeekDates()
  },
  handleUpdateButton(){
    this.update()
  },
  getNowWeek(){
    const nowDate = new Date().getTime();
    const startDate = new Date(this.data.startDate);
    const time = nowDate - startDate;
    const nowWeek = Math.ceil( time /1000 /60 /60 /24 /7 );
    this.setData({
      nowWeek
    });
    this.getWeekDates();
  },
  getData(){
    const cache = wx.getStorageSync('courses')
    if(cache){
      this.setData({
        courseList:cache
      })
      return
    }
    this.update()
  },
  update(){
    const that = this
    getCourseListRequest().then(res =>{
      this.setData({
        courseList:res.data
      })
      wx.getStorageSync(courseCacheKey,res.data)
    })
  },

})